import asyncio
import logging
from datetime import datetime
from ..services.user_service import UserService

logger = logging.getLogger(__name__)

class TokenCleanupTask:
    """令牌清理任务"""
    
    def __init__(self):
        self.user_service = UserService()
        self.is_running = False
    
    async def start_cleanup_task(self):
        """启动清理任务"""
        if self.is_running:
            return
        
        self.is_running = True
        logger.info("启动令牌清理任务")
        
        while self.is_running:
            try:
                # 每小时清理一次过期令牌
                await asyncio.sleep(3600)
                self.user_service.cleanup_expired_refresh_tokens()
                logger.info(f"令牌清理完成: {datetime.utcnow()}")
                
            except Exception as e:
                logger.error(f"令牌清理任务出错: {str(e)}")
                await asyncio.sleep(300)  # 出错后5分钟重试
    
    def stop_cleanup_task(self):
        """停止清理任务"""
        self.is_running = False
        logger.info("停止令牌清理任务")

# 全局实例
token_cleanup_task = TokenCleanupTask()